<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;

/**
 * 文章分类
 *
 * @icon   fa fa-certificate
 * @remark
 */
class ArticleCategory extends Backend
{

    /**
     * @var \app\common\model\ArticleCategory
     */
    protected $model = null;

    protected $isIndexArr=['否','首页样式1','首页样式2','首页样式3','首页样式4'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('ArticleCategory');

        $tree = Tree::instance();
        $tree->init(collection($this->model->order('sort desc,id desc')->select())->toArray(), 'pid');
        $this->articlecategorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $articlecategorydata=array();
        $articlecategorydata[0]='顶级分类';
        if(!empty($this->articlecategorylist)){
            foreach ($this->articlecategorylist as $k => $v) {
                $articlecategorydata[$v['id']] = $v['name'];
            }
        }
        $this->parentlist=$articlecategorydata;
        $this->view->assign("parentList", $articlecategorydata);
    }

    public function index(){

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => &$v) {
                $v['pid']=$v['pid']?$this->model->where('id='.$v['pid'])->value("concat(id,'-',name) as info"):'0-顶级分类';
                $v['isindex']=$v['isindex'].'-'.$this->isIndexArr[$v['isindex']];
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        return parent::edit($ids);
    }
}
